package com.mlf.builder;

import com.mlf.builder.Spring.UserService;
import com.mlf.builder.car.Car;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

public class BuilderPatternExample {
    public static void main(String[] args) {
        // 1. 创建 Spring 容器工厂
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        //2.1 构建car
        registerCar(beanFactory);


        // 2.2 使用建造者构建 BeanDefinition
        BeanDefinitionBuilder builder = BeanDefinitionBuilder
                .genericBeanDefinition(UserService.class)      // 设置 Bean 类
                .setScope("singleton")                         // 设置作用域
                .addPropertyValue("username", "admin")         // 设置属性值
                .addPropertyReference("car", "cr")      // 设置引用其他 Bean
                .setInitMethodName("init")                     // 设置初始化方法
                .setLazyInit(true);                            // 延迟初始化

        // 3. 获取构建完成的 BeanDefinition
        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();

        // 4. 注册到容器
        beanFactory.registerBeanDefinition("userService123", beanDefinition);

        // 5. 从容器获取 Bean 实例
        UserService service = beanFactory.getBean("userService123", UserService.class);
        System.out.println(service.getUsername()); // 输出: admin
    }

    private static void registerCar(DefaultListableBeanFactory beanFactory) {
        BeanDefinitionBuilder crBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(Car.class)
                .addPropertyValue("carName", "宝马")
                .addPropertyValue("length", "333");

        beanFactory.registerBeanDefinition("cr", crBuilder.getBeanDefinition());
    }
}